package org.finesys.codegen.util;

import cn.hutool.core.util.CharsetUtil;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.DateTool;
import org.apache.velocity.tools.generic.MathTool;
import org.finesys.common.core.util.StrUtil;

import java.io.StringWriter;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;

public class VelocityKit {

    /**
     * Velocity 模板渲染方法
     *
     * @param template 模板
     * @param map      数据模型
     * @return 渲染结果
     */
    public static String render(String template, Map<String, Object> map) {
        //设置资源加载器
        Properties properties = new Properties();
        properties.put("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(properties);

        VelocityContext velocityContext = new VelocityContext(map);
        //函数库
        Optional.of(new MathTool()).ifPresent(mathTool -> velocityContext.put("math", mathTool));
        Optional.of(new DateTool()).ifPresent(dateTool -> velocityContext.put("dateTool", dateTool));
        Optional.of(new DictTool()).ifPresent(dictTool -> velocityContext.put("dict", dictTool));
        Optional.of(new StrUtil()).ifPresent(strTool -> velocityContext.put("str", strTool));
        //渲染模版
        StringWriter stringWriter = new StringWriter();
        Optional.of(Velocity.getTemplate(template, CharsetUtil.UTF_8)).ifPresent(tpl -> tpl.merge(velocityContext, stringWriter));
        return stringWriter.toString();
    }

    /**
     * 渲染文本
     *
     * @param str
     * @param map 数据
     * @return 渲染结果
     */
    public static String renderStr(String str, Map<String, Object> map) {
        //设置资源加载器
        Velocity.init();
        VelocityContext velocityContext = new VelocityContext(map);
        //函数库
        Optional.of(new MathTool()).ifPresent(mathTool -> velocityContext.put("math", mathTool));
        Optional.of(new DateTool()).ifPresent(dateTool -> velocityContext.put("dateTool", dateTool));
        Optional.of(new DictTool()).ifPresent(dictTool -> velocityContext.put("dict", dictTool));
        Optional.of(new StrUtil()).ifPresent(strTool -> velocityContext.put("str", strTool));
        //渲染模版
        StringWriter stringWriter = new StringWriter();
        Velocity.evaluate(velocityContext, stringWriter, "renderStr", str);
        return stringWriter.toString();
    }

}
